package cn.edu.zafu.bigdata.x.hjn;

import java.sql.*;

public class DatabaseHelper {
    private static final String URL = "jdbc:mysql://192.168.169.76:3306/learnjava";
    private static final String USER = "learn";
    private static final String PASSWORD = "learnpassword";

    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(URL, USER, PASSWORD);
    }

    // 添加学生信息
    public static boolean addStudent(Student student) {
        String query = "INSERT INTO students (id, name, phone) VALUES (?, ?, ?)";
        try (Connection conn = getConnection();
             PreparedStatement stmt = conn.prepareStatement(query)) {
            stmt.setString(1, student.getId());
            stmt.setString(2, student.getName());
            stmt.setString(3, student.getPhone());
            int rowsAffected = stmt.executeUpdate();
            return rowsAffected > 0;
        } catch (SQLException e) {
            System.out.println("添加学生信息失败: " + e.getMessage());
            return false;
        }
    }

    // 根据学号查询学生
    public static Student getStudentById(String id) {
        String query = "SELECT * FROM students WHERE id = ?";
        try (Connection conn = getConnection();
             PreparedStatement stmt = conn.prepareStatement(query)) {
            stmt.setString(1, id);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                String name = rs.getString("name");
                String phone = rs.getString("phone");
                return new Student(id, name, phone);
            }
        } catch (SQLException e) {
            System.out.println("查询学生信息失败: " + e.getMessage());
        }
        return null;
    }

    // 更新学生信息
    public static boolean updateStudent(Student student) {
        String query = "UPDATE students SET name = ?, phone = ? WHERE id = ?";
        try (Connection conn = getConnection();
             PreparedStatement stmt = conn.prepareStatement(query)) {
            stmt.setString(1, student.getName());
            stmt.setString(2, student.getPhone());
            stmt.setString(3, student.getId());
            int rowsAffected = stmt.executeUpdate();
            return rowsAffected > 0;
        } catch (SQLException e) {
            System.out.println("更新学生信息失败: " + e.getMessage());
            return false;
        }
    }

    // 删除学生信息
    public static boolean deleteStudent(String id) {
        String query = "DELETE FROM students WHERE id = ?";
        try (Connection conn = getConnection();
             PreparedStatement stmt = conn.prepareStatement(query)) {
            stmt.setString(1, id);
            int rowsAffected = stmt.executeUpdate();
            return rowsAffected > 0;
        } catch (SQLException e) {
            System.out.println("删除学生信息失败: " + e.getMessage());
            return false;
        }
    }
}
